<?php

/**
 * Description of UsuarioController
 *
 * @author Márlon
 * OBS: Para utilizar AJAX ao invés de REST extender de Zend_Controller_Action
 */
class API_UsuarioController extends Zend_Rest_Controller {

    protected $_Service;

    public function init() {
        //Geração de json
        $contextSwitch = $this->_helper->getHelper("contextSwitch");
        $contextSwitch->addActionContext("index", array("xml", "json"))->initContext();

        #$this->_helper->viewRenderer->setNoRender(true);
        $this->_Service = new Application_Service_UsuarioService();
    }

    public function indexAction() {
        $result = $this->_Service->search($this->_getAllParams());
        $this->getResponse()->setHttpResponseCode(200);      
        $total = $result['total'];
        
        unset($result['total']);
        
        echo Zend_Json::encode(array(
            "data" => $result,
            "total" => $total,
            "success" => true
        ));        
    }

    public function getAction() {
        $result = $this->_Service->find($this->_getParam("id"));
        if ($result):
            print_r($result->toArray());
        else:
            $this->getResponse()->setHttpResponseCode(404);
        endif;
    }

    public function postAction() {
        $result = $this->_Service->insert($this->_request->getPost());
        if ($result):
            $this->getResponse()->setHttpResponseCode(201);
            echo $result;
        else:
            $this->getResponse()->setHttpResponseCode(404);
        endif;
    }

    public function putAction() {
        parse_str($this->getRequest()->getRawBody(), $params);
        $res = $this->_Service->update($params, $this->_getParam("id"));
        if ($res):
            $result = $this->_Service->find($this->_getParam("id"));
            print_r($result->toArray());
        else:
            $this->getResponse()->setHttpResponseCode(503);
        endif;
    }

    public function deleteAction() {
        $this->getResponse()->setHttpResponseCode(204);
    }

}
